import urequests
import time
import ujson
import ntptime
import mqtt
from mqtt import CLIENT_ID
# 设置阿里云NTP服务器
ntptime.host = "ntp.aliyun.com"


def send_wechat_message(message):
    url = "https://apis.bemfa.com/vb/wechat/v1/wechatWarnJson"
    headers = {
        "Content-Type": "application/json; charset=utf-8"
    }
    data = {
        "uid": CLIENT_ID,
        "device": "智能猫砂盆",
        "message": message,
    }
    try:
        json_data = ujson.dumps(data).encode('utf-8')
        print(f"Sending data: {json_data}")
        response = urequests.post(url, data=json_data, headers=headers)
        if response.status_code != 200:
            raise Exception(f"HTTP error {response.status_code}")
        result = response.json()
        if result.get('code') == 0:
            print("发送消息成功")
        else:
            print(f"发送消息失败，错误信息: {result.get('msg')}")
            print(f"Response details: {response.text}")
        response.close()
        return result
    except ValueError as json_err:
        print(f"解析响应JSON出错: {json_err}")
    except Exception as e:
        print(f"请求出错: {e}")


last_ntp_sync = 0
NTP_SYNC_INTERVAL = 3600  # 每小时同步一次

def get_current_time():
    global last_ntp_sync
    current_timestamp = time.time()
    
    # 检查是否需要同步时间（超过1小时或首次调用）
    if current_timestamp - last_ntp_sync > NTP_SYNC_INTERVAL or last_ntp_sync == 0:
        try:
            ntptime.settime()
            print("时间同步成功")
            last_ntp_sync = current_timestamp
        except Exception as e:
            print(f"时间同步失败: {e}")
    
    # 获取当前时间戳
    current_timestamp = time.time()
    # 将时间戳转换为结构化时间（+8小时时区调整）
    struct_time = time.localtime(current_timestamp + 8 * 3600)

    # 手动格式化日期为 "YYYY-MM-DD HH:MM:SS"
    formatted_date = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
        struct_time[0], struct_time[1], struct_time[2],
        struct_time[3], struct_time[4], struct_time[5]
    )
    print(formatted_date)
    return formatted_date


if __name__ == "__main__":
    mqtt.connect_wifi()
    current_time = get_current_time()
    print(f"测试消息推送，当前时间: {current_time}")

